package com.urerp.web.config;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.InvalidPropertiesFormatException;
import java.util.Locale;
import java.util.Properties;

import javax.servlet.Filter;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.urerp.web.interceptor.SessionInterceptor;
import com.urerp.web.view.JstlView;
 
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.urerp.web")
public class WebConfig extends WebMvcConfigurerAdapter {
	
	private final static Logger logger = LogManager.getLogger(WebConfig.class);
	
	public WebConfig() {
		logger.info("Initialized - WebConfig");
	}
	
	@Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    	configurer.enable();
    }
	
    @Bean
    public InternalResourceViewResolver getInternalResourceViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setViewClass(JstlView.class);
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    	// registry.addResourceHandler("/resources/**").addResourceLocations("classpath:resources/**");
       
    }
    
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
    	registry.addViewController("/").setViewName("home/index");
    	registry.addViewController("/index").setViewName("home/index");
    }

    @Bean
	public Properties code(@Value("classpath:properties/code.properties") Resource propFile) throws InvalidPropertiesFormatException, IOException{

		Properties props = new Properties();
		props.load(propFile.getInputStream());

		return props;
	}
     
    @Bean
    public HttpMessageConverter<String> responseBodyConverter() {
        return new StringHttpMessageConverter(Charset.forName("UTF-8"));
    }

    @Bean
    public Filter characterEncodingFilter() {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);
        return characterEncodingFilter;
    }
    
    
    @Bean
    public SessionInterceptor sessionInterceptor() {
        return new SessionInterceptor();
    }
    
    @Override
	public void addInterceptors(InterceptorRegistry registry) {
    	registry.addInterceptor(sessionInterceptor())
    			.addPathPatterns("/**")
    			.excludePathPatterns("/login/**");

	}
    
    // 메세지 처리
    @Bean
    public MessageSource messageSource() {
    	// 개발용
    	ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
    	messageSource.setCacheSeconds(5);
    	
    	// 라이브
    	// ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("/WEB-INF/messages/messages");
        messageSource.setDefaultEncoding("UTF-8");
        messageSource.setUseCodeAsDefaultMessage(true);
        return messageSource;
    }
    
    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor(){
        LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();

        localeChangeInterceptor.setParamName("lang");
        return localeChangeInterceptor;
    }
    
    @Bean(name = "localeResolver")
    public LocaleResolver sessionLocaleResolver(){
        // 세션 기준으로 로케일을 설정 한다.
        SessionLocaleResolver localeResolver = new SessionLocaleResolver();
       
        // 쿠키 기준(세션이 끊겨도 브라우져에 설정된 쿠키 기준으로)
        // CookieLocaleResolver localeResolver = new CookieLocaleResolver();
        
        // 기본 로케일
        localeResolver.setDefaultLocale(new Locale("ko_KR"));
        return localeResolver;
    }
    
    // jackson
    @Override
	public void configureContentNegotiation(	ContentNegotiationConfigurer configurer) {
		configurer.favorPathExtension(false)
				  .favorParameter(true)
				  .parameterName("mediaType")
				  .ignoreAcceptHeader(true)
				  .useJaf(false)
				  .defaultContentType(MediaType.APPLICATION_JSON)
				  .mediaType("xml",MediaType.APPLICATION_XML)
				  .mediaType("json", MediaType.APPLICATION_JSON);
	}
    
}
